<template>
  <Dialog v-model="dialogVisible" width="800px" title="收货" :before-close="() => closeDialog()">
    <!--    表单-->
    <el-form :model="form" label-width="130px">
      <el-form-item :label="t('order.proofOfReceipt')" prop="voucher">
        <UploadFile
          url="/common/uploadFile"
          upload-file-button-name="点击上传"
          :file-type="['png', 'jpg', 'jpeg', 'bmp']"
          :params="{ directory: 2 }"
          :limit="9"
          list-type="text"
          :show-file-list="true"
          @upload-success-res="handleUploadCallback"
          @handle-remove-file="handleRemoveFile"
          @handle-picture-card-preview="handlePictureCardPreview"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button class="m-r-4" @click="closeDialog">
        {{ t('system.parameterConfig.cancel') }}
      </el-button>
      <el-button type="primary" @click="submit">
        {{ t('order.confirm') }}
      </el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import UploadFile from '@/components/UploadFile/index.vue'
import { Dialog } from '@/components/Dialog'
import { useI18n } from '@/hooks/web/useI18n'
import { ElMessage, ElMessageBox } from 'element-plus'
import { receivingDataApi } from '@/api/order'
import { createImageViewer } from '@/components/ImageViewer'

const emit = defineEmits(['refresh'])
const { t } = useI18n()
const { push } = useRouter()
const { query } = useRoute()

const dialogVisible = ref<boolean>(false)

const form = ref<Record<string, any>>({
  voucher: []
})

const handleRemoveFile = (val: any) => {
  if (form.value.voucher && form.value.voucher.length) {
    form.value.voucher = form.value.voucher.filter(
      (item: Record<string, any>) => item.uploadFile.uid !== val.uid
    )
  }
}

//上传成功以后回调
const handleUploadCallback = (val: any) => {
  form.value.voucher.push(val)
}

const handlePictureCardPreview = (val: any) => {
  if (!val) return
  createImageViewer({
    urlList: [val],
    zIndex: 99999
  })
}

const submit = () => {
  ElMessageBox.confirm(
    '确认收货后订单状态不可回退，请确认无误后谨慎操作。',
    t('purchase.logistics.tips'),
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  )
    .then(async () => {
      const params = JSON.parse(JSON.stringify(form.value))
      params.voucher = params.voucher.map((item: Record<string, any>) => item.id)
      params.order_id = JSON.parse(decodeURIComponent(query.data as string))?.id || ''

      const resp = await receivingDataApi(params)
      if (resp.code === 0) {
        ElMessage.success(t('order.receivingMsg'))
        closeDialog()
        push('/order/order-management')
      }
    })
    .catch(() => {})
}

const closeDialog = () => {
  form.value = {
    voucher: []
  }
  dialogVisible.value = false
}

defineExpose({
  dialogVisible
})
</script>
<style lang="less" scoped></style>
